<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" errorPage="/error.jsp"%>
<%@page import="dbexp.model.Trigger"%>
<%@page import="dbexp.model.db.DbUser"%>
<%@page import="dbexp.connection.DbMetaData"%>
<%@page import="org.json.JSONObject"%>
<%
DbUser u = (DbUser)session.getAttribute("USER");
String name = request.getParameter("name");
String schema = request.getParameter("schema");
boolean nowy = (name==null || name.trim().equals("null")) && (schema==null || schema.trim().equals("null"));
String id = schema+"-"+name;
String action="update";
String source = "\"\"";
String error = "\"\"";
String tableOwner = "";
String tableName = "";
boolean fer = false;
long when = 0;
boolean insert=false,delete=false,update=false;
Trigger ob = null;
if(nowy){
	action="create";
	schema=u.getSchemaName();
	name="Nowy wyzwalacz";
}
String save = "Zapisz";
if(nowy){
	save = "Utwórz";
}else{
	ob = DbMetaData.getTrigger(u, name, schema);
	source = JSONObject.quote(ob.getContent());
	error = JSONObject.quote(ob.getErrorString());
	tableName = ob.getString("table_name");
	tableOwner = ob.getString("table_owner");
	fer = ob.isForEachRow();
	when = ob.getWhen();
	insert = ob.isInsert();
	delete = ob.isDelete();
	update = ob.isUpdate();
}
%>
<div class="container" style="width:500px">
    <div id="<%=id%>-form"></div>
</div>
<script language="JavaScript">
var plsql = new SqlEditor({initialText: <%=source%>});
TriggerForm = Ext.extend(Ext.form.FormPanel, {
    renderTo: '<%=id%>-form',
    iconCls: 'db-trigger-icon',
    frame:true,
    labelAlign: 'left',
    width: 850,
    url:'db/sourcetype/trigger.jsp',
    initComponent : function() {
   		 var config={
        	defaultType: 'textfield',
        	defaults: {
            	anchor: '100%'
       		},
       		defaultType: 'textfield',
       		monitorValid:true,
       		items:[
       			{
           	    	xtype:'tabpanel',
           	    	activeTab: 0,
           	    	resizeTabs: true,
           	        animScroll:false,
           	    	minTabWidth: 135,
        			tabWidth: 135,
					items:[{
						title:'Ogólne',
						layout:'form',
						bodyStyle:'padding:10px',autoHeight:true,
						defaultType: 'textfield',
						frame:true,
						defaults: {
							anchor: '100%'
						},
				        items:[
							{fieldLabel: 'Nazwa', name: 'name', allowBlank: false,value:'<%=name %>'<%=(nowy)?"":",readOnly:true"%>},
       	        			<%=(nowy)?"combo({emptyText:'"+schema+"'}),":"{fieldLabel:'Schema',name:'schema',allowBlank:false,value:'"+schema+"',readOnly:true},"%>
							{xtype:'fieldset',title:'Treść zapytania',layout:'fit',
       	       					 items:plsql
					    	},{xtype:'fieldset',title:'Błędy',layout:'fit',collapsed: true,collapsible:true,
					          items:ta({height:110,name: 'error',disabled:false,allowBlank: true,value:<%=error%>})
					    	}
					    ]
       	        	},{
						title:'Zdarzenie',
						layout:'form',
						bodyStyle:'padding:10px',height:330,
						defaultType: 'textfield',
						frame:true,
						defaults: {
							anchor: '100%'
						},
				        items:[
				        	{
				        		xtype:'radiogroup',
				        		anchor: '65%',
				        		fieldLabel:'Wyzwalacz na',
				        		readOnly:true,
				        		disabled:true,
				        		items:[
				        			{
				        				boxLabel:'Tabeli',
				        				name:'on',
				        				checked:true
				        			},{
				        				boxLabel:'Widoku',
				        				name:'on',
				        			},{
				        				boxLabel:'Schemacie',
				        				name:'on',
				        			},{
				        				boxLabel:'Bazie danych',
				        				name:'on',
				        			}
				        		]
				        	},
       	        			<%=(nowy)?"combo({emptyText:'"+schema+"'}),":"{fieldLabel:'Schemat',name:'tableOwner',allowBlank:false,value:'"+tableOwner+"',readOnly:true},"%>
							{fieldLabel: 'Tabela', name: 'table', allowBlank: false,value:'<%=tableName %>'<%=(nowy)?"":",readOnly:true"%>},
							{
				        		xtype:'radiogroup',
				        		anchor: '45%',
				        		column:'.5',
				        		items:[
				        			{
				        				boxLabel:'Przed zdarzeniem',
				        				name:'when',
				        				checked:<%=(when==0)%>
				        			},{
				        				boxLabel:'Po zdarzeniu',
				        				name:'when',
				        				checked:<%=(when==1)%>
				        			}
				        		]
				        	},{xtype:'checkbox',boxLabel: 'Dla kazdego wiersza', name: 'fer',checked:<%=fer%>},{
					            xtype: 'fieldset',
					            title: 'Triger',
					            width:100,
					            defaultType:'checkbox',
					            default:{fieldLabel:''},
					            fieldLabel:'',
					            allowBlank: false,
					            items: [
					                {fieldLabel:'',boxLabel: 'Wprowadzanie', name: 'insert',checked:<%=insert%>},
					                {fieldLabel:'',boxLabel: 'Usuwanie', name: 'delete',checked:<%=delete%>},
					                {fieldLabel:'',boxLabel: 'Modyfikacja', name: 'update',checked:<%=update%>}
					            ]
					        }
					    ]
       	        	}]
       	        }
       		
       		],
       	    buttons:[{
       	    	text: 'Zapisz',
       	    	iconCls: 'icon-save',
       	    	formBind:true,
       	    	scope: this,
       	    	handler:this.submit
           	},{
           		text: 'Odśwież',
           		scope: this,
                handler: function(btn, ev){
                	this.getForm().load({url:'db/sourcetype/trigger.jsp',params:{name:'${name}',schema:'${schema}',action:'get'},method:'POST'});
            	}
            }]
       };

   		Ext.apply(this, Ext.apply(this.initialConfig, config));
        TriggerForm.superclass.initComponent.apply(this, arguments);
    },
	onRender:function() {
	    TriggerForm.superclass.onRender.apply(this, arguments);
	    this.getForm().waitMsgTarget = this.getEl();
    },
	onLoadClick:function() {
    	this.load({
	    	url:this.url
	    	,waitMsg:'Ładowanie...'
	    	 ,params:{action:'get'}
    	});
    },
    submit:function() {
        var val = plsql.getValue();
    	this.getForm().setValues({source:val});
    	this.getForm().submit({
    		url:this.url,
    		scope:this,
    		success:this.onSuccess,
    		failure:this.onFailure,
    		params:{action:'create'},
    		waitMsg:'Trwa zapisywanie danych...'
    	});
   	},
   	onSuccess:function(form, action) {
   		obj = Ext.util.JSON.decode(action.response.responseText);
        var root = Ext.getCmp('api-tree').getRootNode();
    	if( (catNode=root.findChild("t","1537"))!=null){
    		if( (subCatNode=catNode.findChild("t","593"))!=null){
    			subCatNode.reload();
    		}
    	}
    	this.getForm().findField('error').setValue(obj.data.error);
   		<%if(nowy){%>
   		Ext.Msg.alert('DbExplorer','Z powodzeniem utworzono nowy wyzwalacz');
		var w = Ext.getCmp('create-window');
		if(w){
			w.close();
		}
	<%}%>
    },
    onFailure:function(form, action) {
    		this.showError(action.response.responseText);
    },
    showError:function(msg) {
    	obj = Ext.util.JSON.decode(msg);
    	 title = obj.error.title||'Error';
    	 Ext.Msg.show({
    		title:title,
    	 	msg:obj.error.msg||obj.error,
    	 	modal:true,
    	 	icon:Ext.Msg.ERROR,
    	 	buttons:Ext.Msg.OK
    	 });
    }
});
Ext.onReady(function() {
	Ext.form.Field.prototype.msgTarget = 'side';
    var functionForm = new TriggerForm({
        renderTo: '<%=id%>-form'
    });
});
</script>